/**
 * 解析请求参数
 * @param {*} url
 */
export const parseQuery = url => {
  let query = {};
  if (url.indexOf('?') >= 0) {
    url
      .split('?')[1]
      .split('&')
      .forEach(entry => {
        let _query = entry.split('=');
        query[_query[0]] = _query[1];
      });
  }
  return query;
};

/**
 * 获取时间戳
 * @param {*} time
 * 参数类型： 1，时间字符串 YYYY-MM-DD ,2 时间对象, 3 时间戳，精确到秒
 */
export const getTimeStamp = time => {
  if (typeof time == 'string') {
    var timeArr = time.split(/[- : \/]/);
    let timeObj = new Date(
      timeArr[0],
      timeArr[1] - 1,
      timeArr[2],
      timeArr[3],
      timeArr[4],
      timeArr[5],
    );
    let timeStamp = Math.ceil(timeObj.getTime() / 1000);
    return timeStamp;
  } else if (typeof time == 'object') {
    return Math.ceil(time.getTime() / 1000);
  } else {
    let timeStr = time.toString() || '';
    return timeStr.length > 10 ? Math.ceil(time / 1000) : time;
  }
};
/**
 * 时间戳转时间
 * @param timestamp 时间戳
 * @param isFull 是否需要时分秒
 * @return Promise 对象
 */
export const timeFormat = (timestamp, format = 'YYYY-MM-DD hh:mm:ss') => {
  if (!timestamp) return '';
  var date = new Date(getTimeStamp(timestamp) * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear();
  var M =
    date.getMonth() + 1 >= 10
      ? date.getMonth() + 1
      : '0' + (date.getMonth() + 1);
  var D = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate();
  var h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours();
  var m = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes();
  var s = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds();

  var value = format
    .replace('YYYY', Y)
    .replace('MM', M)
    .replace('DD', D)
    .replace('hh', h)
    .replace('mm', m)
    .replace('ss', s);
  return value;
};

/**
 * 函数节流
 * @param {*} method 需要执行的函数
 * @param {*} duration 间隔时间
 */
export const throttle = (function() {
  var begin = Date.now();
  return function(method, duration) {
    var context = this,
      args = arguments,
      current = Date.now();
    if (current - begin >= duration) {
      method.apply(context, args);
      begin = current;
    }
  };
})();
export const promisify = (func, opts) => {
  return new Promise((resolve, reject) => {
    func({
      ...opts,
      success: resolve,
      fail: reject,
    });
  });
};
export const delay = time => {
  return new Promise(function(r) {
    setTimeout(r, time);
  });
};
export default {
  timeFormat,
};
